//地址栏参数解释
//source 跳转至改页面的来源
//	news 消息列表
//	customer 业务代表
//	help 帮助中心
//	null 微信公众号详情点击进来

//<div class="SysPrompt">显示最近十条信息</div>

var roomNumber;
var leftheadurl; //左边的头像地址
var thistoopenId; // 收取消息的ip
var id;
var ifadmin;

var thistotal = 0; //当前的消息总和
if(GetQueryString("source")) {
	var thissource = GetQueryString("source");
	if(thissource == 'news') {
		roomNumber = GetQueryString("roomNumber");
		oldWindowBengin();
	} else if(thissource == 'customer') {
		var id = GetQueryString("id");
		newWindowBegin('{"id":"'+id+'"}')
	} else if(thissource == 'help'){
		newWindowBegin('{}')
		mui.toast("已为您自动匹配客服");
	}
} else {
	roomNumber = GetQueryString("roomNumber");
	oldWindowBengin();
}



//
//var id ;
//if(GetQueryString("id")){
//	//从咨询页面过来
//	id = GetQueryString("id");
//	newWindowBegin();
//}else if(localStorage.thisroomNumber){
//	//上一次点击过的房间
//	
//}else if(GetQueryString("oldroomNumber")){
//	//从消息页面挪过来
//	oldWindowBengin();
//}else{
////	最新
//	id = null;
//	mui.toast("已为您自动匹配客服");
//}

function newWindowBegin(jsondata) {

//	var id = GetQueryString("id");

	MuiAjaxFn("api/salesman/select?page=1&pagesize=10",jsondata, function(data) {
		//左边客户主动发送信息
		console.log(data)
		if(data.htmlState.status == 200) {

			data = data.pageInfo.list[0];
			//			localStorage.toopenId = data.openId;
			thistoopenId = data.openId;
			if(data.headPhoto.indexOf("http://") == -1 ){
		        //判断当前的头像是否是有htto前缀.
		        data.headPhoto = IMGUrl + '' + data.headPhoto ;
		    }
			
			leftheadurl =  data.headPhoto;
			appendHelpToHtml('left', ' 您好，请问您遇到了什么问题？', leftheadurl);

			$(".mui-title").html(data.salesmanName)

		}
	})

}

function oldWindowBengin() {
	//旧的已经生成的房间点击过来的
	//显示最近的三条聊天记录

	actualTimeFn();
	MuiAjaxFn("client/consulting/selectbymessage?page=1&pagesize=1", {
		'tosort': 'asc',
		'sorting': 'send_time',
		'roomNumber': roomNumber
	}, function(data) {
		if(data.htmlState.status == 200) {
		thistotal = data.pageInfo.total; //最新的赋值总量
		if(data.pageInfo.list[0].fromOpenId == user.getter().openId) {
			//				当前账号是用户
			ifadmin = 0;
			console.log(ifadmin);
			leftheadurl = data.dataResultObj.toInfo.headimgurl;
			thistoopenId = data.dataResultObj.toInfo.openId;
			
		} else {
			//				当前账号是管理员
			ifadmin = 1;
			console.log(data.pageInfo.list[0].fromOpenId == user.getter().openId);
			leftheadurl = data.dataResultObj.fromInfo.headimgurl;
			thistoopenId = data.dataResultObj.fromInfo.openId;
		}
		
		
		
		}
	});
	
	setTimeout(function() {
		MuiAjaxFn("client/consulting/selectbymessage?page=1&pagesize=10", {
		'tosort': 'desc',
		'sorting': 'send_time',
		'roomNumber': roomNumber
	}, function(data) {
		if(data.htmlState.status == 200) {
//			if( data.pageInfo.total > 10 ){
//				$(".HC_dialoguebox").append('<div class="SysPrompt">显示最近十条信息</div>');
//			}
//		 
		$(".mui-title").html(data.dataResultObj.toInfo.nickName);

			$.each(data.pageInfo.list, function(idx, obj) {
				//此处暂时显示时间以此来辨别

				if(obj.toOpenId == user.getter().openId) {
					//当前信息为左侧发送
					appendoldHelpToHtml('left', obj.message , leftheadurl)

				} else {
					appendoldHelpToHtml('right', obj.message, user.getter().headimgurl)

				}

			});

		}
	});
	}, 500)

	
}

//聊天对话视图
function getHelpTemp(type, message, headurl) {
	var typeHtml = type == "left" ? 'HC_business' : 'HC_Customer';
	//found:: 这里还需要添加图片
	
	
	
	return '<div class="' + typeHtml + '"><div class="HC_pic"><div style="background-image:url(' + headurl + ')"></div></div>' +
		'	<span>' + message + '</span>' +
		'</div>';
}

//聊天对话添加 并 置底
function appendHelpToHtml(type, message, url){
//     $(".HC_dialoguebox").scrollTop(scrollHeight,200);
		$(".HC_dialoguebox").append(getHelpTemp(type, message, url));
		var scrollHeight = $(".HC_dialoguebox").prop("scrollHeight");
  		$(".HC_dialoguebox").animate({scrollTop:scrollHeight}, 400);

}


//聊天对话添加 并 置底
function appendoldHelpToHtml(type, message, url) {
	$(".HC_dialoguebox").prepend(getHelpTemp(type, message, url));
	var scrollHeight = $(".HC_dialoguebox").prop("scrollHeight");
  	$(".HC_dialoguebox").animate({scrollTop:scrollHeight}, 400);
}

$(function() {
	$(".HC_dialoguebox").height($(window).height() - 114 - 57 + 'px'); //设置聊天窗口界面的高度
	$(".HC_dialoguebox").scrollTop($(".HC_dialoguebox").height()) //一开始将滚动条调到最底部
		//房间号码判断
	event();

	actualTimeFn();
	
	
	$('#SendCont').keydown(function(e){ 
		if(e.keyCode==13){ 
			$("#SendTalk").trigger()
		} 
	}); 


})

//			window.onload = function() {
//				console.log("sad");
//				var roomNumber = getRequest().roomNumber;
//				AjaxPostFn('/client/consulting/selectbymessage?page=1&pagesize=100', {
//					'tosort': 'asc',
//					'sorting': 'send_time',
//					'roomNumber': roomNumber
//				}, function(jsondata) {
//
//					for(var i = 0; i < jsondata.pageInfo.list.length; i++) {
//						console.log(JSON.stringify(jsondata.pageInfo.list[i].message))
//					}
//
//					console.log(JSON.stringify(jsondata.dataResultObj.fromInfo.headimgurl))
//					console.log(JSON.stringify(jsondata.dataResultObj.toInfo.headimgurl))
//
//					;
//				})
//
//			}

function event() {
	//发送按钮
	$("#SendTalk").on("tap", function() {
		clearInterval(actualTime);
		var text = $("#SendCont").val();
		if(text != '') {
			//添加聊天对话
			appendHelpToHtml("right", text, user.getter().headimgurl);
			$("#SendCont").val('');
			//						console.log($(document).height()-$(window).height())
			//						setTimeout(function(){
			$(".HC_dialoguebox").scrollTop($(".HC_dialoguebox").height())
				//						

			//						},500)
			if(roomNumber) {
				//不是首次发送信息

				if(ifadmin == 1) {
					//管理员
					MuiAjaxFn("client/sys/consulting/reply",

						{
							'message': text,
							'roomNumber': roomNumber,
							'messageType': 'message',
							"userNickname": user.getter().nickName,
						},
						function(data) {
							thistotal++;
							actualTimeFn()

							//						appendHelpToHtml("left", "感谢您的回馈，请稍等.." , leftheadurl);
						});
				} else {
					//用户发送信息
					MuiAjaxFn("client/consulting/followsend", {
						'message': text,
						'roomNumber': roomNumber,
						'messageType': 'message',
						"userNickname": user.getter().nickName,
					}, function(data) {
						thistotal++;
						actualTimeFn()

						//						appendHelpToHtml("left", "感谢您的回馈，请稍等..", leftheadurl);
					});
				}

			} else {
				//首次发送信息
				MuiAjaxFn("client/consulting/firstsend", {
					"fromOpenId": user.getter().openId,
					"toOpenId": thistoopenId,
					"message": text,
					"userNickname": user.getter().nickName,
					"messageType": "message"
				}, function(data) {
					if(data.htmlState.status == 200) {
												thistotal ++;
						data = data.dataResultObj;
						roomNumber = data.roomNumber

						//						appendHelpToHtml("left", "稍等..", leftheadurl);
						actualTimeFn()

					}

				})
			}
		}
	})
}

var actualTime

function actualTimeFn() {

	actualTime = setInterval(function() {
		//		console.log(thistotal)
		if(roomNumber) {
			MuiAjaxFn("client/consulting/selectbymessage?page=1&pagesize=10", {
				'tosort': 'desc',
				'sorting': 'send_time',
				'roomNumber': roomNumber
			}, function(data) {

				var newtotal = data.pageInfo.total; //31
				//				console.log('A' + newtotal)
				if(thistotal < newtotal) {
					var count = newtotal - thistotal;
					for(var i = 0; i < count; i++) {
						thistotal++;
						thisdata = data.pageInfo.list[i]
						if(thisdata.toOpenId == user.getter().openId) {
							//当前信息为左侧发送
							appendHelpToHtml('left', thisdata.message , leftheadurl)

						} else {
							appendHelpToHtml('right', thisdata.message, user.getter().headimgurl)

						}
					}

					//					thistotal = newtotal;
				}

			});

		}

	}, 3000)
}